package com.learn.juc;


import java.util.concurrent.RecursiveTask;

/**
 * ClassName:ForkJoin
 * Package:com.learn.juc
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/28 - 21:06
 * @Version:v1.0
 */
public class ForkJoin extends RecursiveTask<Integer> {
    //拆分的时候插值不能超过10
    private static final Integer VALUE = 10;
    private int begin;//拆分的开始值
    private int end;//拆分的结果值
    private int result;//拆分的结果
    //创建一个有参数的构造
    public ForkJoin(int begin,int end){
        this.begin=begin;
        this.end=end;
    }
    //拆分和合并的操作
    @Override
    protected Integer compute() {
        //判断相加的两个数的值是不是>10
        if((end-begin)<=VALUE){
            //相加操作
            for (int i = begin; i <=end ; i++) {
                result=result+i;
            }
        }else {
            //继续拆分
            int mid = (begin+end)/2;
            //拆分左边
            ForkJoin forkJoin1 = new ForkJoin(begin,mid);
            //拆分右边
            ForkJoin forkJoin2 = new ForkJoin(mid+1,end);
            //调用方法拆分
            forkJoin1.fork();
            forkJoin2.fork();
            //合并结果
            result=forkJoin1.join()+forkJoin2.join();
        }
        return result;
    }
}
